<template>
  <div class="flex flex-col gap-3 flex-1">
    <!-- 顶部提示 -->
    <el-alert
      title="温馨提示：请选择科室和医生后，在右侧选择就诊时间进行预约。预约成功后请按时就诊，如需取消请提前操作。"
      type="info"
      :closable="false"
      show-icon
    />

    <!-- 主要内容区域 -->
    <div class="flex gap-3 flex-1">
      <!-- 左侧科室列表 -->
      <div class="w-1/4 bg-white p-3 rounded-lg">
        <div class="text-lg font-bold mb-3">选择科室</div>
        <el-input
          v-model="searchDepartment"
          placeholder="搜索科室"
          class="mb-3"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-menu
          :default-active="activeDepartment"
          @select="handleDepartmentSelect"
        >
          <el-menu-item-group v-for="(dept, index) in departments" :key="dept.id" :index="index">
            <template #title>
              <div class="text-center">{{ dept.name }}</div>
            </template>
            <el-menu-item v-for="subDept in dept.subDepartments" :key="subDept.id" :index="subDept.id">
              {{ subDept.name }}
            </el-menu-item>
          </el-menu-item-group>
        </el-menu>
      </div>

      <!-- 中间医生列表 -->
      <div class="w-1/3 bg-white p-3 rounded-lg">
        <div class="text-lg font-bold mb-3">选择医生</div>
        <el-input
          v-model="searchDoctor"
          placeholder="搜索医生姓名"
          class="mb-3"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="flex flex-col gap-3">
          <el-card v-for="doctor in filteredDoctors" :key="doctor.id" :class="{'border-primary': selectedDoctor?.id === doctor.id}">
            <div class="flex items-start gap-3">
              <el-avatar :size="64" :src="doctor.avatar" />
              <div class="flex-1">
                <div class="flex items-center justify-between">
                  <span class="text-lg font-bold">{{ doctor.name }}</span>
                  <el-tag :type="doctor.level === '主任医师' ? 'danger' : doctor.level === '副主任医师' ? 'warning' : 'info'">
                    {{ doctor.level }}
                  </el-tag>
                </div>
                <div class="text-gray-500 mt-1">{{ doctor.title }}</div>
                <div class="text-gray-500 mt-1">擅长：{{ doctor.expertise }}</div>
              </div>
            </div>
            <div class="mt-3 flex justify-between items-center">
                <div class="text-orange-500 font-bold">
                    挂号费：￥{{ doctor.fee }}
                </div>
                <el-button type="primary" @click="handleSelectDoctor(doctor)">
                    选择医生
                </el-button>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 右侧排班日历 -->
      <div class="flex-1 bg-white p-3 rounded-lg">
        <div class="text-lg font-bold mb-3">选择就诊时间</div>
        
        <!-- 日期选择 -->
        <div class="flex gap-2 mb-3">
          <el-radio-group v-model="selectedDate" size="large">
            <el-radio-button 
              v-for="date in availableDates" 
              :key="date.value" 
              :value="date.value"
              :class="{'border-primary': selectedDate === date.value}"
            >
              {{ date.label }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 时段选择 -->
        <div v-if="selectedDoctor" class="border rounded-lg p-3">
          <div class="grid grid-cols-2 gap-3">
            <div class="border-r pr-3">
              <div class="font-bold mb-2">上午</div>
              <div class="grid grid-cols-2 gap-2">
                <el-button 
                  v-for="slot in morningSlots" 
                  :key="slot.time"
                  :type="slot.available ? 'primary' : 'info'"
                  :disabled="!slot.available"
                  class="time-slot-btn"
                  @click="handleSelectTimeSlot(slot)"
                >
                  {{ slot.time }}
                  <div class="text-xs">剩余{{ slot.count }}号</div>
                </el-button>
              </div>
            </div>
            <div>
              <div class="font-bold mb-2">下午</div>
              <div class="grid grid-cols-2 gap-2">
                <el-button 
                  v-for="slot in afternoonSlots" 
                  :key="slot.time"
                  :type="slot.available ? 'primary' : 'info'"
                  :disabled="!slot.available"
                  class="time-slot-btn"
                  @click="handleSelectTimeSlot(slot)"
                >
                  {{ slot.time }}
                  <div class="text-xs">剩余{{ slot.count }}号</div>
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="text-center text-gray-500 py-10">
          请先选择医生
        </div>
      </div>
    </div>

    <!-- 预约表单对话框 -->
    <Dialog
      v-model="showReservationDialog"
      title="确认预约信息"
      width="500px"
    >
      <el-form :model="reservationForm" label-width="100px">
        <el-form-item label="就诊科室">
          {{ selectedDepartment?.name }}
        </el-form-item>
        <el-form-item label="就诊医生">
          {{ selectedDoctor?.name }} {{ selectedDoctor?.level }}
        </el-form-item>
        <el-form-item label="就诊时间">
          {{ formatReservationTime }}
        </el-form-item>
        <el-form-item label="就诊人">
          <el-select v-model="reservationForm.patientId" class="w-full">
            <el-option
              v-for="patient in patients"
              :key="patient.id"
              :label="patient.name"
              :value="patient.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约备注">
          <el-input
            v-model="reservationForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请填写病情描述或其他需要说明的信息"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="reservationForm.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex items-center justify-between">
          <div class="text-orange-500">
            挂号费：￥{{ selectedDoctor?.fee || 0 }}
          </div>
          <div>
            <el-button @click="showReservationDialog = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmReservation">
              确认预约
            </el-button>
          </div>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Dialog from '@/components/common/Dialog.vue'

// 搜索关键词
const searchDepartment = ref('')
const searchDoctor = ref('')

// 选中状态
const activeDepartment = ref('')
const selectedDoctor = ref(null)
const selectedDate = ref('')
const selectedTimeSlot = ref(null)
const showReservationDialog = ref(false)

// 科室数据
const departments = ref(
    [
        {
            id: '1',
            name: '内科',
            subDepartments:[
                {
                    id:'1',
                    name:'呼吸内科'
                },{
                    id:'2',
                    name:'消化内科'
                }
            ]
        },
        {
            id: '2',
            name: '外科',
            subDepartments:[
                {
                    id:'1',
                    name:'普通外科'
                },{
                    id:'2',
                    name:'骨科'
                }
            ] 
        },
        {   
            id: '3',
            name: '专科',
            subDepartments:[
                {
                    id:'1',
                    name:'眼科'
                },
                {
                    id:'2',
                    name:'耳鼻喉科'
                }
            ]
        }
])
// 医生数据
const doctors = ref([
  {
    id: '1',
    name: '张医生',
    level: '主任医师',
    title: '内科教授，博士生导师',
    expertise: '呼吸系统疾病，慢性咳嗽，哮喘等',
    avatar: 'https://example.com/avatar1.jpg',
    departmentId: '1',
    fee: 50
  },
  {
    id: '2',
    name: '李医生',
    level: '副主任医师',
    title: '内科副教授',
    expertise: '消化道疾病，胃炎，结肠炎等',
    avatar: 'https://example.com/avatar2.jpg',
    departmentId: '2',
    fee: 30
  }
])

// 就诊人数据
const patients = ref([
  { id: '1', name: '张三' },
  { id: '2', name: '李四' }
])

// 预约表单
const reservationForm = ref({
  patientId: '',
  remark: '',
  phone: ''
})

// 计算属性
const selectedDepartment = computed(() => {
  const allDepartments = [
    ...internalDepartments.value,
    ...surgicalDepartments.value,
    ...specialtyDepartments.value
  ]
  return allDepartments.find(dept => dept.id === activeDepartment.value)
})

const filteredDoctors = computed(() => {
  return doctors.value.filter(doctor => {
    const matchDepartment = doctor.departmentId === activeDepartment.value
    const matchSearch = doctor.name.includes(searchDoctor.value)
    return matchDepartment && matchSearch
  })
})

const availableDates = computed(() => {
  const dates = []
  const today = new Date()
  for (let i = 0; i < 7; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)
    dates.push({
      value: date.toISOString().split('T')[0],
      label: i === 0 ? '今天' : i === 1 ? '明天' : `${date.getMonth() + 1}月${date.getDate()}日`
    })
  }
  return dates
})

const morningSlots = ref([
  { time: '08:30', available: true, count: 5 },
  { time: '09:00', available: true, count: 3 },
  { time: '09:30', available: true, count: 4 },
  { time: '10:00', available: true, count: 2 },
  { time: '10:30', available: false, count: 0 },
  { time: '11:00', available: true, count: 1 }
])

const afternoonSlots = ref([
  { time: '14:00', available: true, count: 5 },
  { time: '14:30', available: true, count: 3 },
  { time: '15:00', available: true, count: 4 },
  { time: '15:30', available: true, count: 2 },
  { time: '16:00', available: false, count: 0 },
  { time: '16:30', available: true, count: 1 }
])

const formatReservationTime = computed(() => {
  if (!selectedDate.value || !selectedTimeSlot.value) return ''
  const date = new Date(selectedDate.value)
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${selectedTimeSlot.value.time}`
})

// 方法
const handleDepartmentSelect = (index) => {
  activeDepartment.value = index
  selectedDoctor.value = null
}

const handleSelectDoctor = (doctor) => {
  selectedDoctor.value = doctor
}

const handleSelectTimeSlot = (slot) => {
  if (!slot.available) return
  selectedTimeSlot.value = slot
  showReservationDialog.value = true
}

const handleConfirmReservation = () => {
  if (!reservationForm.value.patientId) {
    ElMessage.warning('请选择就诊人')
    return
  }
  if (!reservationForm.value.phone) {
    ElMessage.warning('请填写手机号')
    return
  }
  
  ElMessage.success('预约成功！')
  showReservationDialog.value = false
  // 这里添加预约成功后的处理逻辑
}
</script>

<style lang="scss" scoped>
/* 移除按钮的默认左边距 */
:deep(.time-slot-btn) {
  margin-left: 0 !important;
}

</style>

